// 在utils/simpleState.ts中

/**
 * 简单的全局状态管理器
 * 只管理视频播放状态和页面切换
 */
class SimpleStateManager {
  private static instance: SimpleStateManager;

  // 当前页面索引
  private currentPageIndex: number = 0;

  // 视频播放状态
  private isVideoPlaying: boolean = false;

  // 页面切换回调
  private pageChangeCallbacks: ((pageIndex: number) => void)[] = [];

  // 视频状态回调
  private videoStateCallbacks: ((isPlaying: boolean) => void)[] = [];

  constructor() {}

  /**
   * 获取单例实例
   */
  static getInstance(): SimpleStateManager {
    if (!SimpleStateManager.instance) {
      SimpleStateManager.instance = new SimpleStateManager();
    }
    return SimpleStateManager.instance;
  }

  /**
   * 设置当前页面索引
   */
  setCurrentPage(pageIndex: number) {
    console.log(`页面切换: ${this.currentPageIndex} -> ${pageIndex}`);
    this.currentPageIndex = pageIndex;

    // 通知所有监听者
    this.pageChangeCallbacks.forEach(callback => callback(pageIndex));
  }

  /**
   * 获取当前页面索引
   */
  getCurrentPage(): number {
    return this.currentPageIndex;
  }

  /**
   * 设置视频播放状态
   */
  setVideoPlaying(isPlaying: boolean) {
    console.log(`视频播放状态: ${isPlaying}`);
    this.isVideoPlaying = isPlaying;

    // 通知所有监听者
    this.videoStateCallbacks.forEach(callback => callback(isPlaying));
  }

  /**
   * 获取视频播放状态
   */
  getVideoPlaying(): boolean {
    return this.isVideoPlaying;
  }

  /**
   * 添加页面切换监听
   */
  onPageChange(callback: (pageIndex: number) => void) {
    this.pageChangeCallbacks.push(callback);
  }

  /**
   * 添加视频状态监听
   */
  onVideoStateChange(callback: (isPlaying: boolean) => void) {
    this.videoStateCallbacks.push(callback);
  }

  /**
   * 移除页面切换监听
   */
  offPageChange(callback: (pageIndex: number) => void) {
    const index = this.pageChangeCallbacks.indexOf(callback);
    if (index > -1) {
      this.pageChangeCallbacks.splice(index, 1);
    }
  }

  /**
   * 移除视频状态监听
   */
  offVideoStateChange(callback: (isPlaying: boolean) => void) {
    const index = this.videoStateCallbacks.indexOf(callback);
    if (index > -1) {
      this.videoStateCallbacks.splice(index, 1);
    }
  }
}

// 导出单例实例
export const simpleState = SimpleStateManager.getInstance();
